<template>
  <div class="app">
    <Notice></Notice>
    <div class="content">
      <div class="titleTag">{{ pageData.pageName }}</div>
      <a-form layout="inline" class="search-form" :label-col="labelCol">
        <a-form-item label="事件编号">
          <a-input
            v-model="searchForm.eventId"
            placeholder="请输入"
            style="width: 200px; margin-left: 10px"
          />
        </a-form-item>
        <a-form-item label="投诉人电话">
          <a-input
            v-model="searchForm.reporterPhone"
            placeholder="请输入"
            style="width: 200px; margin-left: 10px"
          />
        </a-form-item>
        <a-form-item :label="stateList.name">
          <a-select
            v-model="searchForm[stateList.prop]"
            filterable
            allow-clear
            placeholder="请选择"
            @change="handleStateChange"
            style="width: 200px; margin-left: 10px"
          >
            <a-select-option
              v-for="d in stateList.list"
              :key="d.value"
              :value="d.value"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="上报来源">
          <a-select
            filterable
            allow-clear
            v-model="searchForm.issueSource"
            placeholder="请选择"
            style="width: 200px; margin-left: 10px"
          >
            <a-select-option
              v-for="d in issueSourceList"
              :key="d.value"
              :value="d.label"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="问题类型">
          <a-select
            filterable
            allow-clear
            v-model="searchForm.issueType"
            placeholder="请选择"
            style="width: 200px; margin-left: 10px"
          >
            <a-select-option
              v-for="d in issueTypeList"
              :key="d.value"
              :value="d.label"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="紧急程度">
          <a-select
            filterable
            allow-clear
            v-model="searchForm.urgencyLevel"
            placeholder="请选择"
            style="width: 200px; margin-left: 10px"
          >
            <a-select-option
              v-for="d in urgencyLevelList"
              :key="d.value"
              :value="d.value"
            >
              {{ d.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="上报时间">
          <a-range-picker
            style="width: 330px; margin-left: 10px"
            v-model="dateRange"
            :placeholder="['开始日期', '结束日期']"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            :show-time="{
              hideDisabledOptions: true,
              defaultValue: [
                moment('00:00:00', 'HH:mm:ss'),
                moment('23:59:59', 'HH:mm:ss'),
              ],
            }"
            format="YYYY-MM-DD HH:mm:ss"
            @change="onChange"
          />
        </a-form-item>
        <a-form-item style="float: right">
          <a-button type="primary" @click="handleSearch" class="mr10"
            >查询
          </a-button>
          <a-button type="default" @click="handleReset" class="mr10"
            >重置
          </a-button>
        </a-form-item>
      </a-form>
      <a-tabs
        :default-active-key="pageData.defaultKey"
        @change="changeTab"
        v-if="pageData.tabList && pageData.tabList.length > 0"
      >
        <a-tab-pane
          :tab="item.name"
          v-for="item in pageData.tabList"
          :key="item.value"
        >
        </a-tab-pane>
      </a-tabs>
      <div class="flex-end mb10">
        <a-spin :spinning="autoLoading">
          <a-button
            type="primary"
            @click="handleAutoDispatch"
            v-if="pageType === 'jxhpq'"
            >自动派遣
          </a-button>
        </a-spin>
        <a-spin :spinning="oneLoading">
          <a-button
            :disabled="selectedRowKeys.length < 1"
            type="primary"
            @click="handleDispatch"
            v-if="pageType === 'jxhpq'"
            >一键派遣
          </a-button>
        </a-spin>
      </div>
      <a-spin :spinning="loading">
        <!-- 数据表格 -->
        <div class="table-container">
          <a-table
            :row-selection="rowSelection"
            :columns="columns"
            :data-source="tableData"
            :pagination="false"
            :row-key="(record) => record.eventId"
            @change="handleTableChange"
          >
            <template slot="description" slot-scope="text, record">
              <ToolTip :text="text" />
            </template>
            <template slot="eventId" slot-scope="text, record">
              <span
                class="eventId-cell"
                @click="handleOperation(record, 'Detail')"
                >{{ text }}
              </span>
            </template>
            <template slot="reporterPhone" slot-scope="text, record">
              <div class="phone-cell">
                <span>{{
                  record.showReporterPhone ? text : $desensitizePhone(text)
                }}</span>
                <a-icon
                  :type="record.showReporterPhone ? 'eye-invisible' : 'eye'"
                  @click.stop="togglePhoneVisibility1(record)"
                />
              </div>
            </template>
            <template slot="urgencyLevel" slot-scope="text, record">
              <span
                class="img-item"
                :class="{
                  'urgency-level': true,
                  'level-0': text == '0',
                  'level-1': text == '1',
                  'level-2': text == '2',
                }"
              >
                {{
                  (
                    (urgencyLevelList &&
                      urgencyLevelList.find((item) => item.value == text)) ||
                    {}
                  ).label || ""
                }}
                <!-- {{text}} -->
                <!-- v-show="text.dubanStatus==1"  -->
                <img
                  v-show="record.dubanStatus == 1"
                  src="https://head-image-1259022270.cos.ap-guangzhou.myqcloud.com/head-image-7797f7c8-b335-4a99-b4fa-f4cba5dc875f督办.png"
                  class="dubanImg"
                />
              </span>
            </template>
            <!-- 操作列 -->
            <template slot="operation" slot-scope="text, record">
              <a-space>
                <a-button type="link" @click="handleOperation(record, 'Detail')"
                  >案件详情
                </a-button>
              </a-space>
            </template>
          </a-table>
        </div>

        <div class="page_box">
          <a-pagination
            v-model="pageParams.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total"
            show-size-changer
            :page-size="pageParams.current"
            @showSizeChange="onShowSizeChange"
            @change="pageChange"
            :show-total="(total) => `共 ${total} 条`"
          ></a-pagination>
        </div>
      </a-spin>
      <a-modal
        :visible="modalVisible"
        title="一键派遣"
        @ok="handleOk"
        @cancel="modalVisible = false"
      >
        <a-spin :spinning="formLoading">
          <a-form
            ref="dialogFormRef"
            :form="dialogFormResp"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-form-item label="派遣部门">
              <a-tree-select
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择派遣部门"
                tree-default-expand-all
                v-decorator="[
                  'deptId',
                  { rules: [{ required: true, message: '请选择派遣部门' }] },
                ]"
              >
              </a-tree-select>
            </a-form-item>
          </a-form>
        </a-spin>
      </a-modal>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import dictMixin from "@/mixins/dictMixin";
import moment from "moment";
import Notice from "@/component/notice.vue";


export default {
  name: "WdsbIndex",
  mixins: [dictMixin],
  components: {
    Notice,
  },
  props: {
    pageType: {
      type: String,
      default: "Report",
    },
    pageData: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    stateList() {
      let list = [];
      let name = "";
      let prop = "";
      switch (this.pageType) {
        case "wdsb":
          list = [
            { label: "暂存", value: "0" },
            { label: "已上报", value: "1" },
            { label: "直接办结", value: "2" },
          ];
          name = "受理状态";
          prop = "businessStatus";
          break;
        case "jxhpq":
          list = [
            { label: "待派遣", value: "1" },
            { label: "待部门受理", value: "2" },
          ];
          name = "办理状态";
          prop = "eventStatus";
          break;
        case "ajsl":
          list = [
            { label: "待受理", value: "2" },
            { label: "已驳回", value: "20" },
          ];
          name = "派遣状态";
          prop = "pqStatus";
          break;
        case "wdpqd":
          list = [
            { label: "待确认", value: "30" },
            { label: "已确认", value: "31" },
            { label: "待审核", value: "33" },
          ];
          name = "派遣状态";
          prop = "pqStatus";
          break;
        case "pqdsh":
          list = [
            { label: "待审核", value: "33" },
            { label: "驳回返工", value: "40" },
          ];
          name = "办理状态";
          prop = "pqStatus";
          break;
        case "ajsh":
          list = [
            { label: "待审核", value: "4" },
            { label: "已通过", value: "5" },
            { label: "驳回返工", value: "50" },
          ];
          name = "办理状态";
          prop = "eventStatus";
          break;
        case "ajgd":
          list = [
            { label: "待归档", value: "5" },
            { label: "已归档", value: "6" },
          ];
          name = "办理状态";
          prop = "eventStatus";
          break;
        case "ajgz":
          list = [
            { label: "待指挥中心派遣", value: "1" },
            { label: "待部门受理", value: "2" },
            { label: "部门派遣", value: "3" },
            { label: "部门办结审核", value: "4" },
            { label: "指挥中心审核", value: "5" },
            { label: "返工", value: "50" },
            { label: "结案", value: "51" },
            { label: "归档", value: "6" },
            { label: "已回访", value: "7" },
          ];
          name = "办理状态";
          prop = "eventStatus";
          break;
      }
      return {
        list,
        name,
        prop,
      };
    },
    rowSelection() {
      if (this.pageType === "jxhpq") {
        return {
          selectedRowKeys: this.selectedRowKeys || [],
          onChange: this.onSelectChange,
        };
      }
      return null;
    },
  },
  data() {
    return {
      modalVisible: false,
      labelCol: { style: { width: "70px", mariginLeft: "20px" } },
      wrapperCol: { justify: "space-between" },
      // 搜索表单数据
      searchForm: {
        eventId: "",
        reporterPhone: "",
        // businessStatus: undefined,
        issueType: undefined,
        urgencyLevel: undefined,
        startTime: "",
        endTime: "",
      },
      dateRange: [],
      // 表格数据
      tableData: [],
      // 表格列定义
      columns: [
        {
          title: "事件编号",
          dataIndex: "eventId",
          key: "eventId",
          width: 195,
          scopedSlots: { customRender: "eventId" },
        },
        {
          title: "问题来源",
          dataIndex: "issueSource",
          key: "issueSource",
          width: 100,
        },
        {
          title: "问题类型",
          dataIndex: "issueType",
          key: "issueType",
          width: 100,
        },
        {
          title: "紧急程度",
          dataIndex: "urgencyLevel",
          key: "urgencyLevel",
          width: 150,
          scopedSlots: { customRender: "urgencyLevel" },
        },
        {
          title: ['ajsl','pqdsh','wdpqd'].includes(this.pageType) ? "部门办理状态":"受理状态",
          dataIndex: "businessStatus",
          key: "businessStatus",
          width: 120,
          customRender: (text, record, index) => {
            return (
              (this.businessStatusList.find((item) => item.value == text) || {})
                .label || ""
            );
          },
        },
        {
          title: "办理状态",
          dataIndex: "eventStatus",
          key: "eventStatus",
          width: 100,
          customRender: (text, record, index) => {
            return (
              (this.dealStatusList.find((item) => item.value == text) || {})
                .label || ""
            );
          },
        },
        {
          title: "关联对象",
          dataIndex: "relatedObjectName",
          key: "relatedObjectName",
          width: 100,
          scopedSlots: { customRender: "description" },
        },
        {
          title: "案件描述",
          dataIndex: "issueDescription",
          key: "issueDescription",
          width: 100,
          scopedSlots: { customRender: "description" },
        },
        {
          title: "上报人姓名",
          dataIndex: "reporterName",
          key: "reporterName",
          width: 100,
        },
        {
          title: "上报人电话",
          dataIndex: "reporterPhone",
          key: "reporterPhone",
          width: 120,
          scopedSlots: { customRender: "reporterPhone" },
        },
        {
          title: "上报时间",
          dataIndex: "reportTime",
          key: "reportTime",
          width: 100,
        },
        {
          title: "操作",
          key: "operation",
          width: 100,
          scopedSlots: { customRender: "operation" },
        },
      ],

      loading: false,
      pageParams: {
        current: 20,
        offset: 1,
      },
      total: 0,
      excelFlag: "0",
      selectedRowKeys: [],
      autoLoading: false,
      oneLoading: false,
      dialogFormResp: this.$form.createForm(this),
      formLoading: false,
      treeData: [],
      // ----------------------------信息
      currentIndex: 0,
      itemHeight: 40, // 单个项的高度（需与 CSS 一致）
      offsetindex: 0,
      timer: null,
      msgList:[],

      // ------------------------------------信息
    };
  },
  mounted() {
    // this.getmsgList();

    this.getDictData({
      code: "QUESTION_SOURCE_CODE", // 问题来源
      name: "issueSourceList",
    });
    this.getDictData({
      code: "QUESTION_TYPE_CODE", // 问题类型
      name: "issueTypeList",
    });
    this.searchForm[this.stateList.prop] = this.stateList.list[0].value;
    this.getTableData();
  },
  created() {
    // 每次进入组件时进行初始化
    this.initializeData();
  },
  beforeUnmount() {
    this.stopScroll();
  },
  methods: {
    moment,
    startScroll() {
      this.timer = setInterval(() => {
        if(this.msgList.length > 0){
          clearInterval(this.timer);
          return
        }
        // 计算下一个索引
        this.currentIndex = (this.currentIndex + 1) % this.msgList.length;
        // 更新偏移量
        this.offsetindex = -this.currentIndex * this.itemHeight;
      }, 2000); // 2秒切换一次
    },
    stopScroll() {
      clearInterval(this.timer);
    },
    getmsgList() {
     
      const url = "/government-platform-center/leader/getPublicMsg";
      this.$axios
        .post(url, {
            current: 40,
            offset: 1,
            isRead: 0,
          }, 
          {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          
          if (res.data.code == 0 && res.data.data.length > 0 ) {
            console.log('消息消息=====',res.data.data)
            res.data.data.map(v=>{
              this.msgList.push(v.title)
            })
            this.startScroll();

          }
        });
    },
    handleStateChange(val){
      this.$set(this.searchForm, this.stateList.prop, val);
      this.$forceUpdate();
    },
    handleAutoDispatch() {
      this.autoLoading = true;
      this.$axios
        .post(`/government-platform-center/case/robotExcePaiQian`)
        .then((res) => {
          if (res.data.code === 0) {
            this.$message.success("操作成功");
          }
        })
        .finally(() => {
          this.autoLoading = false;
        });
    },
    handleDispatch() {
      this.modalVisible = true;
      this.getDeptTree();
    },
    async getDeptTree() {
      this.formLoading = true;
      await this.$axios
        .get("/government-platform-center/dept", {
          params: { current: 1000, offset: 1 },
        })
        .then((res) => {
          if (res.data.code === 0) {
            const targetData = this.transformTreeData(res.data.data || []);
            this.treeData = targetData;
          }
        })
        .finally(() => {
          this.formLoading = false;
        });
    },
    transformTreeData(data) {
      function transformNode(node) {
        return {
          value: node.id,
          title: node.thisData.deptName,
          parentId: node.parentId,
          children: (node.childList || []).map(transformNode),
          ...node.thisData, // 将其他属性也保留下来
        };
      }

      return data.map(transformNode);
    },
    // 一键派遣提交
    handleOk() {
      this.dialogFormResp.validateFields((err, values) => {
        if (err) return;
        this.formLoading = true;
        let data = new FormData();
        data.append("deptId", values.deptId);
        data.append("eventIdList", this.selectedRowKeys);
        this.$axios
          .post(`/government-platform-center/case/oneExcePaiQian`, data)
          .then((res) => {
            if (res.data.code === 0) {
              this.$message.success("操作成功");
              this.modalVisible = false;
              this.getTableData();
            }
          })
          .finally(() => {
            this.formLoading = false;
          });
      });
    },

    changeTab(val) {
      this.excelFlag = val;
      this.getTableData();
    },
    onChange(val) {
      this.searchForm.startTime = val[0];
      this.searchForm.endTime = val[1];
    },
    initializeData() {
      // 重置所有相关数据到初始状态
      this.formData = {};
      this.tableData = [];
      this.total = 0;
      this.pageParams = {
        current: 20,
        offset: 1,
      };
      // 如果有查询条件，也需要重置
      if (this.searchForm) {
        this.searchForm = {};
      }
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.pageParams.current = pageSize;
      this.pageParams.offset = current;
      this.getTableData();
    },
    pageChange(current) {
      this.pageParams.offset = current;
      this.getTableData();
    },
    getTableData() {
      this.loading = true;
      let targetData = {
        ...this.searchForm,
        ...this.pageParams,
      };
      if (this.pageData.tabList && this.pageData.tabList.length > 0) {
        targetData.excelFlag = this.pageData.excelFlag;
        targetData = {
          ...targetData,
          exceFlag: this.excelFlag,
        };
      }
      let data = qs.stringify(targetData);
      this.$axios[this.pageData.method](
        `/government-platform-center${this.pageData.apiUrl}`,
        data
      )
        .then((res) => {
          if (res.data.code === 0) {
            this.tableData = res.data.data || [];
            this.total = res.data.total || 0;
            // 清空选中的数据
            this.selectedRowKeys = [];
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 查询
    handleSearch() {
      this.pageParams.offset = 1;
      this.getTableData();
    },
    // 重置
    handleReset() {
      this.dateRange = [];
      this.searchForm = {
        eventId: "",
        reporterPhone: "",
        [this.stateList.prop]: this.stateList.list[0].value,
        issueType: undefined,
        urgencyLevel: undefined,
        reportTime: "",
      };
      this.getTableData();
    },
    togglePhoneVisibility1(record) {
      this.$set(record, "showReporterPhone", !record.showReporterPhone);
    },
    // 查看详情
    handleOperation(row, type) {
      this.$router.push({
        path: "/xuncha/zhsldd/detail",
        query: {
          id: row.eventId,
          operationType: type,
          pageType: this.pageType,
          paramId: row[this.pageData.paramId],
        },
      });
    },
    // 处理表格变化
    handleTableChange(pag) {
      this.pageParams.current = pag.current;
      // 加载新数据
    },
    // 勾选
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },

    // 获取状态标签颜色
    getStatusColor(status) {
      const colorMap = {
        暂存: "blue",
        已上报: "green",
        紧急: "red",
      };
      return colorMap[status] || "default";
    },
    handTap(type){
      // this.$emit('jumpTo', type);
       this.$router.push({
        path: type
      });

    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  height: 40px;
  line-height: 40px;
  background: #fff;
  padding: 0 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}

.content {
  padding: 10px;
  background: #fff;
  border-radius: 5px;
  height: calc(100vh - 140px);
  overflow-y: auto;

  .titleTag {
    // font-size: 20px;
    // font-weight: 500;
    // margin: 20px 0;
    // color: #4285f4;
    font-size: 18px;
    font-weight: 500;
    margin: 10px 0;
  }

  .search-form {
    padding: 10px;
    margin-bottom: 20px;
  }
}

.table-container {
  width: 100%;
  overflow-x: auto;
  position: relative;

  /* 处理Spin组件层级 */
  ::v-deep .ant-spin-nested-loading {
    overflow: visible !important;
  }

  ::v-deep .ant-spin-container {
    position: static !important;
  }
}

/* 强制表格渲染宽度 */
.ant-table {
  min-width: 1900px !important;

  /* 固定列特殊处理 */
  .ant-table-fixed-columns-in-body {
    visibility: visible !important;
  }
}

/* 强制显示滚动条轨道 */
.table-container {
  scrollbar-width: thin; /* Firefox */

  &::-webkit-scrollbar {
    height: 8px;
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
  }
}

.urgency-level {
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;

  &.level-0 {
    background-color: #1890ff;
    color: #fff;
  }

  &.level-1 {
    background-color: #f7f588;
    color: #000;
  }

  &.level-2 {
    background-color: #ff4d4f;
    color: #fff;
  }
}
::v-deep .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold !important;
}
.dubanImg {
  width: 25px;
  height: 25px;
  display: inline-block;
  position: absolute;
  top: -2px;
  right: -28px;
}
.img-item {
  position: relative;
}


.scroll-container {
  height: 40px; /* 显示区域高度 */
  overflow: hidden;
  cursor: pointer;
}
.scroll-content {
  transition: transform 1.5s ease; /* 平滑过渡动画 */
}
.item {
  height: 40px;
  line-height: 40px;
  text-align: left;
  display: flex;
  align-items: center;
}
.item img{
  width: 20px;
  height: 20px;
  // margin-right: 10px;
}
.item .imgs{
  position: relative;
}
.item .imgs .yuan{
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: absolute;
  top: 14px;
  right: 4px;
  background-color: red;
}
.eventId-cell {
  color: #1890ff;
  font-weight: 400;
  font-size: 14px;
  cursor: pointer;
}

</style>
